//
//  RHMePlantInfoVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/3.
//

#import "RHMePlantMonitorVC.h"
#import "RHMePlantInfoCell.h"
#import "RHMePlantTopoCell.h"
#import "RHPlantInfoChartCell.h"
#import "RHDeviceListViewController.h"
#import "RHDeviceStatusVC.h"
#import "RHDeviceBindVC.h"
#import "DevChartParamsModel.h"
#import "DevChartModel.h"
#import "SYChartTool.h"
#import "WSDatePickerView.h"
#import "RHMePlantInfoFullChartVC.h"
#import "DeviceChartFieldModel.h"
#import "IFMMenu.h"
#import "RHEditPlantVC.h"
#import "RHPlantTransferVC.h"
#import "RHMePlantInfoChartCell.h"
#import "RHMePlantInfoAlarmCell.h"

#import "RHDeviceModel.h"
#import "RHDeviceStatusVC.h"
#import "RHPlantInfoTopoFullScreenVC.h"
#import <MGSwipeTableCell.h>
#import "KWTMGRNSettingVC.h"
#import "RHEndPointTypeModel.h"
#import "RHEndPointModel.h"
#import "KWTPlantMasterDeviceListVC.h"
#import "KWT233KInvSettingVC.h"
#import "RHMePlantDetailInfoVC.h"
#import "RHMeDeviceInfoVC.h"
#import "RHMePlantDetailModel.h"
#import "RHMePolicySetVC.h"
#import "RHMePriceSetVC.h"
#import "RHTools.h"
#import "KWT233KInvSettingVC.h"
#import "RHSolarkSettingVC.h"
#import "RHHiSolarSettingVC.h"
#import "SettingsViewController.h"

@interface RHMePlantMonitorVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic, strong) RHMePlantDetailModel *detailModel;

@property (nonatomic ,strong) DevChartParamsModel *chartParamsModel;

//节能减排
@property (nonatomic ,strong) NSDictionary *emissionReductionDic;

@property (nonatomic ,strong) IFMMenu *menu;

@property (nonatomic ,strong) NSDictionary *addressDic;
@end

@implementation RHMePlantMonitorVC

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.menu dismissMenu];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    self.navigationItem.title = self.plantModel.plantName;
  
    [self createData];
    [self setupUI];
    [self getData];
    
}

-(void)createData
{
    NSArray *lineColors = @[@[@"#FF902A"],@[@"#46ECA6",@"#678EF2"],@[@"#8269F1",@"#5296FD"]];
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"ME_PlantEnergyStatistics"];
    self.chartParamsModel = [DevChartParamsModel yy_modelWithDictionary:dict];
    NSArray *chartTitles = @[@"收益曲线".rh_localized,@"充放电量趋势".rh_localized,@"SOC曲线".rh_localized];
    [chartTitles enumerateObjectsUsingBlock:^(NSString*  _Nonnull title, NSUInteger idx, BOOL * _Nonnull stop) {
       DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:idx];
        chartModel.title = title;
        chartModel.colorArr = [lineColors safeObjectAtIndex:idx];
        //收益曲线不能选择今日
//        if ([title isEqualToString:@"收益曲线".rh_localized]) {
//            NSDate *lastDate = [[NSDate date]dateBySubtractingDays:1];
//            chartModel.curTime = [NSString stringWithFormat:@"%ld",(NSInteger)[lastDate timeIntervalSince1970]];
//        }
    }];
}

-(void)getData
{
    [self getChartData];
    [self getPlantMonitorDetail];
    [self getPlantDetail];
}

//获取电站详情,取城市地址
-(void)getPlantDetail
{
    NSString *url = [NSString stringWithFormat:@"%@/%ld",H_plantDetail,self.plantModel.plant_id];
    [RHPlantModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSArray *addressKeys = @[@"countryId",@"countryName",@"stateId",@"stateName",@"cityId",@"cityName"];
            NSDictionary *dic =request.responseJSONObject[@"data"];
          //去掉空值,有的没有城市
            NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
            [addressKeys enumerateObjectsUsingBlock:^(NSString*  _Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
                if (![dic[key] isEqual:[NSNull null]]) {
                    [dicM setObject:dic[key] forKey:key];
                }
            }];
            self.addressDic = dicM.copy;
            
            RHPlantModel *plantModel = resultModel.data;
            if (plantModel.deviceTypeCode.length>0) {
                self.plantModel.plantType = plantModel.deviceTypeCode;
                self.plantModel.productTypeId = plantModel.productTypeId;
                self.plantModel.productTypeCode = plantModel.productTypeCode;
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

-(void)getChartData
{
    for ( NSInteger i = 0;i < self.chartParamsModel.chartList.count;i++) {
        DevChartModel *chartModel = self.chartParamsModel.chartList[i];
        if (i == 0) {
            [self getIncomeStatisticsWithChartModel:chartModel];
        }else{
            [self getEnergyStatisticsWithChartModel:chartModel];
        }
        
    }
}

#pragma mark ------ 电站监控详情数据
-(void)getPlantMonitorDetail
{
    NSDictionary *para = @{@"plantId":@(self.plantModel.plant_id)};
    [RHMePlantDetailModel startGetWithCompletionAPIKey:H_MeplantMonitorDetail argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if (resultModel.code == 200) {
            self.detailModel = resultModel.data;
           
            self.navigationItem.title = self.detailModel.plantName;
            [self.tableView reloadData];
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}


-(void)getDataWithChartModel:(DevChartModel*)chartModel index:(NSInteger)index
{
    if (index == 0) {//故障告警次数
        [self getIncomeStatisticsWithChartModel:chartModel];
    }else{
        [self getEnergyStatisticsWithChartModel:chartModel];
    }
}

#pragma mark ----- 能量统计(收益)
-(void)getIncomeStatisticsWithChartModel:(DevChartModel*)chartModel
{
    NSString *type = @"day";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    
    NSTimeZone *zone  = [NSTimeZone systemTimeZone];
    if(chartModel.timeType == TimeType_Day){
        type = @"day";
    }else if (chartModel.timeType == TimeType_Month){
        type = @"month";
    }else if (chartModel.timeType == TimeType_Year){
        type = @"year";
    }
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"plantId":@(self.plantModel.plant_id),@"currentTime":@(currentTime),@"dateRange":type,@"timeZone":zone.name};
    [BaseModel startWithCompletionAPIKey:H_MePlantIncomeData argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {

        chartModel.allDataArray = request.responseJSONObject[@"data"];
//        chartModel.allDataArray = [chartModel getTestData];
        
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}

#pragma mark ----- 能量统计(充放电 SOC)
-(void)getEnergyStatisticsWithChartModel:(DevChartModel*)chartModel
{
    NSString *type = @"day";
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSInteger currentTime = [date timeIntervalSince1970]*1000;
    
    NSTimeZone *zone  = [NSTimeZone systemTimeZone];
    if(chartModel.timeType == TimeType_Day){
        type = @"day";
    }else if (chartModel.timeType == TimeType_Month){
        type = @"month";
    }else if (chartModel.timeType == TimeType_Year){
        type = @"year";
    }
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"plantId":@(self.plantModel.plant_id),@"currentTime":@(currentTime),@"dateRange":type,@"timeZone":zone.name};
    [BaseModel startWithCompletionAPIKey:H_getRegularStatisticsByPlant argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {

        chartModel.allDataArray = request.responseJSONObject[@"data"];
//        chartModel.allDataArray = [chartModel getTestData];
        
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:3] withRowAnimation:UITableViewRowAnimationNone];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
        
    }];
}


- (void)setupUI{
    kWeakSelf;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getPlantMonitorDetail) name:PlantInfoDidChangeNotification object:nil];

    self.navigationItem.rightBarButtonItem = [UIBarButtonItem qmui_itemWithImage:[[UIImage imageNamed:@"kwt_plant_more"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] target:self action:@selector(rightBarButtonDown)];

    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = CFTabViewBgColor;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHMePlantInfoCell class] forCellReuseIdentifier:@"RHMePlantInfoCell"];
    [_tableView registerClass:[RHMePlantTopoCell class] forCellReuseIdentifier:@"RHMePlantTopoCell"];
    [_tableView registerClass:[RHMePlantInfoChartCell class] forCellReuseIdentifier:@"RHMePlantInfoChartCell_lineChart"];
    [_tableView registerClass:[RHMePlantInfoChartCell class] forCellReuseIdentifier:@"RHMePlantInfoChartCell_lineChart_day"];
    [_tableView registerClass:[RHMePlantInfoChartCell class] forCellReuseIdentifier:@"RHMePlantInfoChartCell_barChart"];
    [_tableView registerClass:[RHMePlantInfoAlarmCell class] forCellReuseIdentifier:@"RHMePlantInfoAlarmCell"];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [_tableView addHeaderRefresh:^{
        [weakSelf getData];
    }];
}

//导航栏弹出
- (void)rightBarButtonDown
{
    kWeakSelf;
   NSMutableArray *menuItems = [[NSMutableArray alloc] initWithObjects:
                  
                  [IFMMenuItem itemWithImage:[UIImage imageNamed:@"me_plant_info"]
                                       title:@"电站信息".rh_localized
                                      action:^(IFMMenuItem *item) {
                        [weakSelf mePlantInfo];
                    }],
                  [IFMMenuItem itemWithImage:[UIImage imageNamed:@"plant_edit_02"]
                                     title:@"编辑电站".rh_localized
                                    action:^(IFMMenuItem *item) {
                      [weakSelf editPlant];
                   
                  }],
                    [IFMMenuItem itemWithImage:[UIImage imageNamed:@"plant_device_list"]
                                       title:@"设备列表".rh_localized
                                      action:^(IFMMenuItem *item) {
                        [weakSelf deviceListOfPlant];
                     
                    }],
                  [IFMMenuItem itemWithImage:[UIImage imageNamed:@"me_plant_strategy_set"]
                                       title:@"策略设置".rh_localized
                                      action:^(IFMMenuItem *item) {
                        [weakSelf policyConfig];
                       
                  }],
                    [IFMMenuItem itemWithImage:[UIImage imageNamed:@"me_plant_price_set"]
                                         title:@"电价设置".rh_localized
                                        action:^(IFMMenuItem *item) {
                          [weakSelf priceConfig];
                    
                    }],nil];
   
    IFMMenu *menu = [[IFMMenu alloc] initWithItems:menuItems];
    menu.menuCornerRadiu = 8;
    menu.showShadow = YES;
    menu.minMenuItemHeight = 45;
    menu.titleColor = [UIColor colorWithHexString:@"3F4443" alpha:0.6];
    menu.titleFont = [UIFont systemFontOfSize:15];
    menu.menuBackgroundStyle = IFMMenuBackgroundStyleLight;
    [menu showFromNavigationController:self.navigationController WithX:[UIScreen mainScreen].bounds.size.width-32];
    self.menu = menu;
}

//电站信息
-(void)mePlantInfo
{
    kWeakSelf;
    RHMePlantDetailInfoVC *plantDetailVC = [[RHMePlantDetailInfoVC alloc]init];
    plantDetailVC.plantModel = self.plantModel;
    plantDetailVC.modifySuccessBlock = ^{
        [weakSelf getPlantMonitorDetail];
    };
    [self.navigationController pushViewController:plantDetailVC animated:YES];
}

#pragma mark ------ 编辑电站
-(void)editPlant{
    kWeakSelf;
    RHMePlantDetailInfoVC *plantDetailVC = [[RHMePlantDetailInfoVC alloc]init];
    plantDetailVC.plantModel = self.plantModel;
    plantDetailVC.isEdit = YES;
    plantDetailVC.modifySuccessBlock = ^{
        [weakSelf getPlantMonitorDetail];
    };
    [self.navigationController pushViewController:plantDetailVC animated:YES];
}

#pragma mark ------ 策略设置
-(void)policyConfig{
    RHMePolicySetVC *vc = [[RHMePolicySetVC alloc]init];
    vc.plantId = self.plantModel.plant_id;
    vc.addressDic = self.addressDic;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark ------ 电价设置
-(void)priceConfig
{
    RHMePriceSetVC *vc = [[RHMePriceSetVC alloc]init];
    vc.plantModel = self.plantModel;
    vc.addressDic = self.addressDic;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ------ 添加设备
-(void)addDeviceToPlant
{
    RHDeviceBindVC *bindDeviceVC = [[RHDeviceBindVC alloc]init];
    bindDeviceVC.plantModel = self.plantModel;
    [self.navigationController pushViewController:bindDeviceVC animated:YES];
}

#pragma mark ------ 设备列表
-(void)deviceListOfPlant
{
    RHDeviceListViewController *vc = [[RHDeviceListViewController alloc] init];
    vc.plantModel = self.plantModel;
    if([PrivateMange share].currentUser.hierarchyCode == UserRoleTypeTerminalUser){
        //如果是终端用户,显示添加设备按钮
        vc.showAddBtn = YES;
        //如果是终端用户,才可以解绑设备
        vc.canDelete = YES;
    }else{
        vc.canDelete = NO;
    }
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ------1. 充放电配置  获取电站下的主设备
-(void)getPlantMasterDevice
{
    [QMUITips showLoadingInView:self.view];
    [RHDeviceModel startGetWithCompletionAPIKey:H_getMasterDeviceIds argument:@{@"plantId":@(self.plantModel.plant_id)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if (resultModel.code == 200) {
            
//            KWTPlantMasterDeviceListVC *masterDevListVC = [[KWTPlantMasterDeviceListVC alloc]init];
//            masterDevListVC.deviceArr = self.deviceArr;
//            [self.navigationController pushViewController:masterDevListVC animated:YES];
//            return;
            //一个设备直接进配置页面
            NSArray *arr = resultModel.data;
            if (arr.count == 1) {
                RHDeviceModel *device = arr.firstObject;
                [self getEndPointReration:device];
            }else if(arr.count>1){
                //进设备列表
                KWTPlantMasterDeviceListVC *masterDevListVC = [[KWTPlantMasterDeviceListVC alloc]init];
                masterDevListVC.deviceArr = arr;
                [self.navigationController pushViewController:masterDevListVC animated:YES];
            }else{
                //没有设备
                [QMUITips showInfo:@"当前电站下无可配置的设备".rh_localized];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
      
}

#pragma mark -----1. 获取设备端点关系 -------
- (void)getEndPointReration:(RHDeviceModel*)device{
    [QMUITips showLoadingInView:self.view];
    NSString *url = [NSString stringWithFormat:@"%@/%@",H_getDevRelationTypeList,SafeStr(device.deviceId)];
    [RHEndPointTypeModel startGetWithCompletionAPIKey:url argument:@{} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
        
            NSArray *typeArr = resultModel.data;
            
            __block BOOL canConfig = NO;
            [typeArr enumerateObjectsUsingBlock:^(RHEndPointTypeModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                //已经配置了的逆变器类型
                NSArray *allInvType = [RHTools allConfigedInverterType];
                //根据逆变器类型处理
                if ([allInvType containsObject:obj.endpoint]&&obj.nodes.count>0) {
                    RHEndPointModel *invEndpoint = [obj.nodes firstObject];
                    if ([invEndpoint.endpoint isEqualToString:InvType_InvMegarevoLv12KW]) {
                        KWTMGRNSettingVC *settingVC = [[KWTMGRNSettingVC alloc]initWithDeviceModel:device endpoint:invEndpoint];
                        [self.navigationController pushViewController:settingVC animated:YES];
                        
                    }else if([invEndpoint.endpoint isEqualToString:InvType_PCS_BCS_B_HM_USX2]){
                        KWT233KInvSettingVC *settingVC = [[KWT233KInvSettingVC alloc]initWithDeviceModel:device endpoint:invEndpoint];
                        [self.navigationController pushViewController:settingVC animated:YES];
                        
                    }else if ([invEndpoint.endpoint isEqualToString:InvType_Sol_Ark_30K_3P_208V]||
                        [invEndpoint.endpoint isEqualToString:InvType_Sol_Ark_60K_3P_480V]) {//61度电 Solark
                        RHSolarkSettingVC *solisVC = [[RHSolarkSettingVC alloc]initWithDeviceModel:device endpoint:invEndpoint];
                        [self.navigationController pushViewController:solisVC animated:YES];
                        
                    }else if([invEndpoint.endpoint isEqualToString:InvType_InvHISOLAR15KW]){//海索
                        RHHiSolarSettingVC *hiSolarVC = [[RHHiSolarSettingVC alloc]initWithDeviceModel:device endpoint:invEndpoint];
                        [self.navigationController pushViewController:hiSolarVC animated:YES];
                        
                    }else if ([invEndpoint.endpoint isEqualToString:InvType_InvVoltronicLv6KW]||
                              [invEndpoint.endpoint isEqualToString:InvType_InvVoltronicLv12KW]) {
                        //逆变器工作模式设置
                        SettingsViewController *rryVC = [[SettingsViewController alloc]init];
                        rryVC.title = @"工作模式设置".rh_localized;
                        rryVC.deviceModel = device;
                        rryVC.endPointTypeModel = obj;
                        [self.navigationController pushViewController:rryVC animated:YES];
                    }
                }
                
            }];
            if (canConfig == NO) {
                [QMUITips showInfo:@"当前电站下无可配置的设备".rh_localized];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
    
    
}

#pragma mark ------- 2.获取逆变器类型 ---------
-(void)getIverterType:(RHEndPointTypeModel*)endPointTypeModel device:(RHDeviceModel *)device
{
    if (endPointTypeModel.nodes.count==0) {
        return;
    }
    RHEndPointModel *endpointModel = [endPointTypeModel.nodes firstObject];
    [QMUITips showLoadingInView:self.view];
    [BaseModel startGetWithCompletionAPIKey:H_getParamStatusData argument:@{@"deviceId":ValidNullData(device.deviceId),@"sn":ValidNullData(endpointModel.sn)} requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if(resultModel.code == 200){
            device.inverterType = (DevInverterType)[request.responseJSONObject[@"data"][@"Inv_DevType"] integerValue];
             if(device.inverterType == DevInverterTypeMGRN7K||
                device.inverterType == DevInverterTypeMGRN12K){
                 KWTMGRNSettingVC *settingVC = [[KWTMGRNSettingVC alloc]initWithDeviceModel:device endpoint:endPointTypeModel.nodes.firstObject];
                
                 [self.navigationController pushViewController:settingVC animated:YES];
             }else{
                 [QMUITips showInfo:@"当前电站下无可配置的设备".rh_localized];
             }

        }
        
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
       
        
    }];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 3) {
        return self.chartParamsModel.chartList.count;
    }
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

   return nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 2) {
        return 15;
    }
    if (section == 3) {
        return 10;
    }
    return 0.0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        RHMePlantInfoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoCell"];
        cell.model = self.detailModel;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }else if(indexPath.section == 1){
        kWeakSelf;
        //拓扑图
        RHMePlantTopoCell *topoCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantTopoCell"];
        
        [topoCell setDetailModel:self.detailModel productType:self.plantModel.productTypeId];
        topoCell.clickDeviceBlock = ^(RHDeviceModel *model) {
            RHMeDeviceInfoVC *deviceInfoVC = [[RHMeDeviceInfoVC alloc]init];
            deviceInfoVC.devModel = model;
            [weakSelf.navigationController pushViewController:deviceInfoVC animated:YES];
        };
        topoCell.selectionStyle = UITableViewCellSelectionStyleNone;
   
        return topoCell;
    }else if (indexPath.section == 2){
        RHMePlantInfoAlarmCell *alarmCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoAlarmCell"];
        alarmCell.detailModel = self.detailModel;
        return alarmCell;
    }else if(indexPath.section == 3){
        kWeakSelf;
        //能量统计
        RHMePlantInfoChartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoChartCell_lineChart"];
        if(indexPath.row == 1) {
            cell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoChartCell_barChart"];
        }else if (indexPath.row == 2) {//soc只有日曲线
            cell = [tableView dequeueReusableCellWithIdentifier:@"RHMePlantInfoChartCell_lineChart_day"];
        }
        DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexPath.row];
        [cell setChartModel:chartModel];
        //选择参数
        cell.selectTopToolBlock = ^(NSInteger index) {
            [weakSelf selectTopTool:index atIndexpath:indexPath];
        };
        
        cell.subTimeBlock = ^{//日期往前
            [weakSelf subTimeAction:indexPath];
        };
        
        cell.addTimeBlock = ^{//日期往后
            [weakSelf addTimeAction:indexPath];
        };
        
        cell.changeTimeBlock = ^{//选择日期
            [weakSelf changeDate:indexPath];
        };
        
        //全屏
        cell.fullChartBlock = ^{
            [weakSelf fullAction:indexPath.row];
        };
        cell.contentView.backgroundColor = CFTabViewBgColor;
        [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        return cell;
    }
    return [UITableViewCell new];
}



//M1001RE1001011     DEV1691735407840   DEV1691735407840  DEV1691735407840
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
   
}


#pragma mark ----------------- Action --------------------
#pragma mark ----- 参数 , 年 , 月 , 日选项 -------------
//工具选择项
- (void)selectTopTool:(NSInteger)index atIndexpath:(NSIndexPath *)indexpath{
    
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexpath.row];
    
    
    if (index == 0) {//Day
        chartModel.timeType = TimeType_Day;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.dayParams;
        [self.tableView reloadData];
       
    }else if (index == 1) {//Month
        chartModel.timeType = TimeType_Month;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.monthParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 2) {//Year
        chartModel.timeType = TimeType_Year;
        NSDate *date = [NSDate date];
        NSTimeInterval interval = [date timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
        chartModel.params = chartModel.yearParams;
        chartModel.allDataArray = @[];
        [self.tableView reloadData];
        
    }else if (index == 4) {//Total
        chartModel.timeType = TimeType_Total;
       
    }
    
    [self getDataWithChartModel:chartModel index:indexpath.row];

}
#pragma mark ------ 选择日期 ------
//变更日期
- (void)changeDate:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexpath.row];
   
    WSDateStyle dataStyle = DateStyleShowYearMonthDay;
    if (chartModel.timeType == TimeType_Day) {
        dataStyle = DateStyleShowYearMonthDay;
    }else if (chartModel.timeType == TimeType_Month){
        dataStyle = DateStyleShowYearMonth;
    }else if (chartModel.timeType == TimeType_Year){
        dataStyle = DateStyleShowYear;
    }

    @weakify(self);
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    WSDatePickerView *datePickerV = [[WSDatePickerView alloc] initWithDateStyle:dataStyle scrollToDate:date CompleteBlock:^(NSDate *selectDate) {
        @strongify(self);
        //NSString *currentDate = [selectDate stringWithFormat: dateFormatStr];//年-月-日-时-分
        NSUInteger timeSp = [selectDate timeIntervalSince1970];
        chartModel.curTime = [NSString stringWithFormat:@"%d",(int)timeSp];
        
       
        [self getDataWithChartModel:chartModel index:indexpath.row];
       
    }];
    datePickerV.dateLabelColor = FontColor(@"#3ECE80");//年-月 颜色
    datePickerV.datePickerColor = UIColorBlack;//滚轮日期颜色
    datePickerV.doneButtonColor = UIColor.blackColor;//确定按钮的颜色
    
    
    if (chartModel.timeType == TimeType_Day) {
        //收益曲线不能选择今日
//        if ([chartModel.title isEqualToString:@"收益曲线".rh_localized]) {
//            NSDate *lastDate = [[NSDate date]dateBySubtractingDays:1];
//            datePickerV.maxLimitDate = lastDate;
//        
//        }
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }else if (chartModel.timeType == TimeType_Month){

    }else if (chartModel.timeType == TimeType_Year){
        datePickerV.maxLimitDate = [NSDate date];
        datePickerV.minLimitDate = [NSDate dateWithYear:[NSDate date].year-5 month:[NSDate date].month day:[NSDate date].day hour:[NSDate date].hour minute:[NSDate date].minute second:[NSDate date].second];
    }
    [datePickerV show];
}
#pragma mark ------ 后一天 -------
//日期累加
- (void)addTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexpath.row];
  
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateByAddingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateByAddingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateByAddingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%ld",(long)interval];
   
    [self getDataWithChartModel:chartModel index:indexpath.row];
    
}

#pragma mark ------ 前一天 -------
//日期累减
- (void)subTimeAction:(NSIndexPath *)indexpath{
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:indexpath.row];
   
    
    if (chartModel.timeType == TimeType_Total) {
        return;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:[chartModel.curTime integerValue]];
    NSDate *nextDate;
    if (chartModel.timeType == TimeType_Day) {
        nextDate = [date dateBySubtractingDays:1];
    }else if (chartModel.timeType == TimeType_Month){
        nextDate = [date dateBySubtractingMonths:1];
    }else if (chartModel.timeType == TimeType_Year){
        nextDate = [date dateBySubtractingYears:1];
    }
    NSTimeInterval interval = [nextDate timeIntervalSince1970];
    chartModel.curTime = [NSString stringWithFormat:@"%d",(int)interval];
    
    
    [self getDataWithChartModel:chartModel index:indexpath.row];
   
}


#pragma mark ---- 全屏
- (void)fullAction:(NSInteger)index{
    DevChartModel *chartModel = [self.chartParamsModel.chartList safeObjectAtIndex:index];
    
    NSInteger type = 2;
    if (chartModel.monthParams.count>0) {
        type = 1;
    }
    if (chartModel.yearParams.count>0) {
        type = 0;
    }
    if (index == 2) {//soc只有日曲线
        type = 2;
    }
    DevChartModel *fullModel = [chartModel modelCopy];
    fullModel.isAllowScale = YES;
    NSString *url = H_getRegularStatisticsByPlant;//充放电 SOC
    if (index == 0) {
        url = H_MePlantIncomeData;//收益
    }
    RHMePlantInfoFullChartVC *vc = [[RHMePlantInfoFullChartVC alloc] initWithModel:fullModel plantModel:self.plantModel toolType:type isBarChart:index == 1 requestUrl:url];
    [self.navigationController pushViewController:vc animated:NO];
   
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}



@end
